package com.UKIT.airtickets.Service.Handlers

import android.content.Context
import androidx.core.content.edit
import androidx.room.Room
import com.UKIT.airtickets.DB.AppDatabase
import com.UKIT.airtickets.DB.User
import com.UKIT.airtickets.Service.SettingsApp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.launch
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

interface AuthenticatorCallbacks {
    fun onAuthenticationSuccess()
    fun onAuthenticationFailure()
}

class Authenticator(private val context: Context, private val callbacks: AuthenticatorCallbacks) {

    private val dbManager = UserDatabaseManager(context)
    private val coroutineScope = CoroutineScope(Dispatchers.IO)

    fun authenticate(login: String, password: String) {
        coroutineScope.launch {
            val user = dbManager.getUserByLogin(login)

            if (user != null && user.password == password) {
                SettingsApp.userId = user.id
                saveUserId(user.id.toInt())
                callbacks.onAuthenticationSuccess()
            } else {
                callbacks.onAuthenticationFailure()
            }
        }
    }

    private fun saveUserId(userId: Int) {
        val sharedPreferences = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE)
        sharedPreferences.edit {
            putInt("user_id", userId)
        }
    }

    fun cancelJobs() {
        coroutineScope.coroutineContext.cancelChildren()
    }
}

class UserDatabaseManager(private val context: Context) {

    private val db: AppDatabase by lazy {
        Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "airtickets.db")
            .fallbackToDestructiveMigration()
            .build()
    }

    suspend fun getUserByLogin(login: String): User? {
        return suspendCoroutine { continuation ->
            CoroutineScope(Dispatchers.IO).launch {
                try {
                    val user = db.userDao().getUserByLogin(login)
                    continuation.resume(user)
                } catch (e: Exception) {
                    continuation.resumeWithException(e)
                }
            }
        }
    }

}
